package org.bob.learn.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Slf4j
public enum RedisUtils {

    INSTANCE;

    private static ReactiveStringRedisTemplate redisTemplate;

    /**
     * Redis底层对象
     */
    @Component
    final static class Redis {
        Redis(ReactiveStringRedisTemplate redisTemplate) {
            RedisUtils.redisTemplate = redisTemplate;
        }
    }

    public static ReactiveStringRedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public static Mono<Boolean> exists(String key) {
        return redisTemplate.hasKey(key);
    }

    public static Mono<Long> unlink(String ...key) {
        return redisTemplate.unlink(key);
    }

    public static Mono<Duration> ttl(String key) {
        return redisTemplate.getExpire(key);
    }

    public static Mono<Boolean> set(String key, String value) {
        return redisTemplate.opsForValue().set(key, value);
    }


    public static Mono<Boolean> set(String key, String value, Duration timeout) {
        return redisTemplate.opsForValue().set(key, value, timeout);
    }

    public static Mono<Boolean> setex(String key, String value) {
        return redisTemplate.opsForValue().setIfPresent(key, value);
    }

    public static Mono<Boolean> setex(String key, String value, Duration timeout) {
        return redisTemplate.opsForValue().setIfPresent(key, value, timeout);
    }

    public static Mono<Boolean> setnx(String key, String value) {
        return redisTemplate.opsForValue().setIfAbsent(key, value);
    }

    public static Mono<Boolean> setnx(String key, String value, Duration timeout) {
        return redisTemplate.opsForValue().setIfAbsent(key, value, timeout);
    }

    public static Mono<Long> pfadd(String key, String ...value) {
        return redisTemplate.opsForHyperLogLog().add(key,value);
    }

    public static Mono<Long> pfcount(String ...key) {
        return redisTemplate.opsForHyperLogLog().size(key);
    }

    public static Mono<Boolean> pfmerge(String destKey,String ...sourceKey) {
        return redisTemplate.opsForHyperLogLog().union(destKey,sourceKey);
    }
}